import { useState, useEffect, useRef } from 'react';
import {
  Button,
  Input,
  Form,
  message,
  InputNumber,
  DatePicker,
  Checkbox,
  Space,
  Col,
  Row,
} from 'antd';
import request from '@/utils/request';
import CateComp from '@/components/CategoryComponent';
import { DeptSelect, EmpSelect } from '@/components/FormItemSelect';
import moment from 'moment';
import { FormattedMessage, useIntl } from 'umi';
import QuerySelect from '@/components/QuerySelect';

const apiURL = '/api/services/app/Demands/';

const DemandEntry = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState({ openLine: true, approve: false });
  const [act, setAct] = useState('New');
  const formRef = useRef<any>();
  const intl = useIntl();

  useEffect(() => {
    props.onRef(this);
    if (props.id) {
      fetchDatas(props.id);
    }
  }, [props.id]);

  const onFinish = (values: any) => {
    const model = values.model;
    setLoading(true);
    model.reqDate = model.reqDate.format('YYYY-MM-DD');
    request(apiURL + act, {
      method: 'POST',
      data: model,
    }).then((response) => {
      if (response) {
        if (response.success) {
          message.success(intl.formatMessage({ id: 'pages.save.success' }));
          const result = response.result;
          result.reqDate = moment(result.reqDate);
          formRef.current.setFieldsValue({ result });
          props.fetchData();
          if (act === 'New') {
            formRef.current.resetFields();
          }
        }
        setLoading(false);
      }
    });
  };

  const fetchDatas = (id: number) => {
    if (id > 0) {
      request(apiURL + 'Get', {
        method: 'GET',
        params: { Id: id },
      }).then((response) => {
        const model = response?.result;
        if (model.reqDate) model.reqDate = moment(model.reqDate);
        formRef.current.setFieldsValue({ model });
        setAct('Modify');
        setData(model);
      });
    }
  };

  const setCurrentPart = (part?: any) => {
    if (part) {
      const model: any = {};
      model.partNum = part.PartNum;
      model.partDescription = part.PartDescription;
      model.ium = part.IUM;
      formRef.current.setFieldsValue({ model });
    }
  };

  const resetForm = () => {
    setAct('New');
    setData({ openLine: true, approve: false });
    formRef.current.resetFields();
  };

  const layout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 15 },
  };

  return (
    <>
      <Form {...layout} ref={formRef} onFinish={onFinish}>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item name={['model', 'id']} label={intl.formatMessage({ id: 'pages.reqNum' })}>
              <Input disabled style={{ width: 200 }} />
            </Form.Item>
            <Form.Item label={intl.formatMessage({ id: 'pages.partNum' })} required>
              <Input.Group compact>
                <Form.Item
                  noStyle
                  name={['model', 'partNum']}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'pages.partNum.required' }) }]}
                >
                  <Input style={{ width: 120 }} disabled />
                </Form.Item>
                <Form.Item noStyle>
                  <QuerySelect
                    width={680}
                    sysReportName="PartSearch"
                    text={<FormattedMessage id="pages.select" />}
                    title={<FormattedMessage id="pages.partNum" />}
                    btntype="primary"
                    setCurrent={setCurrentPart}
                    scroll={{ x: 'max-content', y: '200px' }}
                    params={{ InActive: 'false' }}
                  />
                </Form.Item>
              </Input.Group>
            </Form.Item>
            <Form.Item
              name={['model', 'partDescription']}
              label={intl.formatMessage({ id: 'pages.partDescription' })}
              rules={[{ required: true, message: intl.formatMessage({ id: 'pages.partDescription.required' }) }]}
            >
              <Input disabled />
            </Form.Item>
            <Form.Item label={intl.formatMessage({ id: 'pages.reqQty' })} required={true}>
              <Input.Group compact>
                <Form.Item
                  noStyle
                  name={['model', 'reqQty']}
                  rules={[{ required: true, message: intl.formatMessage({ id: 'pages.reqQty.required' }) }]}
                >
                  <InputNumber min={0} />
                </Form.Item>
                <Form.Item noStyle name={['model', 'ium']}>
                  <Input style={{ width: 60 }} placeholder={intl.formatMessage({ id: 'pages.IUM' })} disabled />
                </Form.Item>
              </Input.Group>
            </Form.Item>
            <Form.Item
              name={['model', 'reqDate']}
              label={intl.formatMessage({ id: 'pages.reqDate' })}
              rules={[{ required: true, message: intl.formatMessage({ id: 'pages.reqDate.required' }) }]}
            >
              <DatePicker />
            </Form.Item>

            <Form.Item wrapperCol={{ offset: layout.labelCol.span }}>
              <Space>
                <Button
                  type="primary"
                  htmlType="submit"
                  disabled={data.approve || !data.openLine}
                >
                  {intl.formatMessage({ id: 'pages.save' })}
                </Button>
                <Button type="default" danger onClick={() => resetForm()}>
                  {intl.formatMessage({ id: 'pages.reset' })}
                </Button>
              </Space>
            </Form.Item>
          </Col>
          <Col span={12}>
            <DeptSelect
              width={200}
              rules={[{ required: true, message: <FormattedMessage id="pages.department.required" /> }]}
              name={['model', 'department']}
              label={<FormattedMessage id="pages.department" />}
            />
            <EmpSelect
              rules={[{ required: true, message: <FormattedMessage id="pages.reqUser.required" /> }]}
              width={200}
              name={['model', 'reqUser']}
              label={intl.formatMessage({ id: 'pages.reqUser' })}
              showSearch
            />
            <Form.Item name={['model', 'commentText']} label={intl.formatMessage({ id: 'pages.commentText' })}>
              <Input.TextArea />
            </Form.Item>
            <CateComp
              layout="reqType"
              width={170}
              name={['model', 'reqType']}
              label={intl.formatMessage({ id: 'pages.reqType' })}
              required
              rules={[
                { required: true, message: <FormattedMessage id="pages.reqType.required" /> },
              ]}
            />
            <Form.Item wrapperCol={{ offset: layout.labelCol.span }} style={{ marginBottom: 0 }}>
              <Input.Group compact>
                <Form.Item name={['model', 'approve']} valuePropName="checked">
                  <Checkbox disabled>{intl.formatMessage({ id: 'pages.approve' })}</Checkbox>
                </Form.Item>
                <Form.Item name={['model', 'openLine']} valuePropName="checked">
                  <Checkbox disabled>{intl.formatMessage({ id: 'pages.openline' })}</Checkbox>
                </Form.Item>
              </Input.Group>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </>
  );
};

export default DemandEntry;
